package com.koron.ticket.line.work.common.service;

import cn.hutool.core.collection.CollUtil;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.workflow.bean.properties.WorkflowProperties;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.ticket.line.work.common.bean.FourteenTables;
import com.koron.ticket.line.work.enums.TicketStatus;
import com.koron.ticket.line.work.workticket.bean.WorkTicket;
import com.koron.ticket.line.work.workticket.bean.WorkTicketQuery;
import com.koron.ticket.line.work.workticket.service.WorkTicketService;
import com.koron.ticket.line.workChange.ticketchange.bean.TicketChange;
import com.koron.ticket.line.workChange.ticketchange.service.TicketChangeService;
import com.koron.ticket.utils.StringUtils;
import com.koron.ticket.work.workPermit.bean.WorkPermit;
import com.koron.ticket.work.workPermit.bean.WorkPermitQuery;
import com.koron.ticket.work.workPermit.service.WorkPermitService;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workend.bean.WorkEndQuery;
import com.koron.ticket.work.workend.service.WorkEndService;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.bean.WorkFlowQuery;
import com.koron.ticket.work.workflow.service.WorkFlowService;
import com.koron.ticket.work.workinfo.bean.WorkInfo;
import com.koron.ticket.work.workinfo.bean.WorkInfoQuery;
import com.koron.ticket.work.workinfo.service.WorkInfoService;
import com.koron.ticket.work.worklocation.bean.WorkLocationBean;
import com.koron.ticket.work.worklocation.service.WorkLocationService;
import com.koron.ticket.work.workmember.bean.WorkMember;
import com.koron.ticket.work.workmember.bean.WorkMemberQuery;
import com.koron.ticket.work.workmember.service.WorkMemberService;
import com.koron.ticket.work.workteam.bean.WorkTeam;
import com.koron.ticket.work.workteam.bean.WorkTeamQuery;
import com.koron.ticket.work.workteam.service.WorkTeamService;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("lineFourteenTablesService")
public class FourteenTablesService {

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    private static Date currentTime = new Date();

    @Autowired
    private WorkTicketService lineWorkTicketService;

    @Autowired
    private WorkInfoService workInfoService;

    @Autowired
    private WorkTeamService workTeamService;

    @Autowired
    private WorkMemberService workMemberService;

    @Autowired
    private WorkLocationService worklocationservice;

    @Autowired
    private WorkFlowHandler workFlowHandler;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private WorkPermitService workPermitService;

    @Autowired
    private WorkEndService workEndService;

    @Autowired
    private TicketChangeService ticketChangeService;

    /**
     * 填写-保存数据
     * 1. workTicketId为空是新增
     * 2. workTicketId不为空是更新
     *
     * @param factory
     * @param fourteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FourteenTables
     */
    public String writeSave(SessionFactory factory, FourteenTables fourteenTables) {
        WorkTicket workTicket = fourteenTables.getWorkTicket();
        String workTicketId = workTicket.getId();

        // 1. 如果id为空，说明是新增
        if (StringUtils.isBlank(workTicketId)) {
            // 1.1 先设置工作票的填写状态
            workTicket.setStatus(1);
            // 1.2 将预览标志设置为未预览
            workTicket.setPreviewFlag(0);
            workTicketId = this.insert(factory, fourteenTables);
        }  // 2. 如果id不为空，说明数据已存在，对现有的数据进行更新
        else {
            lineWorkTicketService.checkTimeOut(factory, workTicketId, fourteenTables.getWorkTicket().getUpdateTime());//检查信息是否过期
            this.update(factory, fourteenTables);
        }
        return workTicketId;
    }

    /**
     * 新增四张表的数据
     * 1. 工作票主票-w_ticket_work
     * 2. 工作票详情-w_ticket_work_info
     * 3. 工作班组-w_ticket_work_team（可以多个）
     * 4. 工作班组成员-w_ticket_work_member（可以多个）
     *
     * @param factory
     * @param fourteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FourteenTables
     */
    @Transactional(rollbackFor = Exception.class)
    public String insert(SessionFactory factory, FourteenTables fourteenTables) {
        Date currentTime = new Date();
        String workTicketId = CodeTools.getCode32();
        WorkTicket workTicket = fourteenTables.getWorkTicket();
        WorkInfo workInfo = fourteenTables.getWorkInfo();
        List<WorkTeam> workTeamList = fourteenTables.getWorkTeamList();
        List<WorkMember> workMemberList = fourteenTables.getWorkMemberList();
        List<WorkLocationBean> workLocationList = fourteenTables.getWorkLocationList();

        // 1. 新增工作票主票的数据
        workTicket.setId(workTicketId);
        workTicket.setDeleteFlag(0);
        workTicket.setCreateUserId(getCurrUser().getId());
        workTicket.setCreateUserName(getCurrUser().getName());
        workTicket.setCreateTime(currentTime);
        workTicket.setCreateDept(getCurrUser().getOrgId());
        workTicket.setCreateDeptName(getCurrUser().getOrgName());
        lineWorkTicketService.insert(factory,workTicket);
        // 2. 新增工作票详情的数据
        workInfo.setId(CodeTools.getCode32());
        workInfo.setWorkTicketId(workTicketId);
        workInfo.setDeleteFlag(0);
        workInfo.setCreateTime(currentTime);
        workInfoService.insert(factory,workInfo);
        // 3. 新增工作班组的相关信息
        if(CollUtil.isNotEmpty(workTeamList)){
            workTeamList.stream().forEach(w->{
                w.setWorkTicketId(workTicketId);
                w.setId(CodeTools.getCode32());
                w.setDeleteFlag(0);
                w.setCreateTime(currentTime);
            });
            workTeamService.batchInsert(factory, workTeamList);
        }
        // 4. 新增工作班组成员的相关信息
        // 20211115: 一级/二级动火工作票没有工作班组成员的信息
        if (CollUtil.isNotEmpty(workMemberList)) {
            workMemberList.stream().forEach(w->{
                w.setWorkTicketId(workTicketId);
                w.setId(CodeTools.getCode32());
                w.setDeleteFlag(0);
                w.setCreateTime(currentTime);
            });
            workMemberService.batchInsert(factory, workMemberList);
        }
        if (CollUtil.isNotEmpty(workLocationList)) {
            workLocationList.stream().forEach(w->{
                w.setWorkTicketId(workTicketId);
                w.setId(CodeTools.getCode32());
                w.setDeleteFlag(0);
                w.setCreateTime(currentTime);
            });
            worklocationservice.batchInsert(factory, workLocationList);
        }

        return workTicketId;
    }

    /**
     * 更新四张表的数据
     * 1. 工作票主票-w_ticket_work
     * 2. 工作票详情-w_ticket_work_info
     * 3. 工作班组-w_ticket_work_team（可以多个）
     * 4. 工作班组成员-w_ticket_work_member（可以多个）
     *
     * @param factory
     * @param fourteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FourteenTables
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(SessionFactory factory, FourteenTables fourteenTables) {
        WorkTicket workTicket = fourteenTables.getWorkTicket();
        WorkInfo workInfo = fourteenTables.getWorkInfo();
        String workTicketId = workTicket.getId();
        List<WorkTeam> workTeamList = fourteenTables.getWorkTeamList();
        List<WorkMember> workMemberList = fourteenTables.getWorkMemberList();
        List<WorkLocationBean> workLocationList = fourteenTables.getWorkLocationList();

        // 1. 更新工作票主票
        // 1.1 添加更新用户id，更新用户名称，更新时间
        workTicket.setUpdateUserId(getCurrUser().getId());
        workTicket.setUpdateUserName(getCurrUser().getName());
        workTicket.setUpdateTime(currentTime);
        lineWorkTicketService.update(factory, workTicket);
        // 2. 更新工作票详情
        workInfoService.update(factory,workInfo);
        // 3. 更新工作班组
        // 3.1 删除原来的工作班组
        workTeamService.deleteByWorkTicketId(factory, workTicketId);
        // 3.2 再新增现在的工作班组
        if(StringUtils.isNotEmpty(workTeamList)){
            workTeamList.stream().forEach(w->{
                w.setWorkTicketId(workTicketId);
                w.setId(CodeTools.getCode32());
                w.setDeleteFlag(0);
                w.setCreateTime(currentTime);
            });
            workTeamService.batchInsert(factory, workTeamList);
        }
        // 4. 更新工作班组成员
        // 4.1 删除原来的工作班组成员
        workMemberService.deleteByWorkTicketId(factory,workTicketId);
        // 4.2 再新增现在的工作班组成员
        // 20211115: 一级/二级动火工作票没有工作班组成员的信息
        if (StringUtils.isNotEmpty(workMemberList)) {
            workMemberList.stream().forEach(w->{
                w.setId(CodeTools.getCode32());
                w.setDeleteFlag(0);
                w.setCreateTime(currentTime);
            });
            workMemberService.batchInsert(factory, workMemberList);
        }
        //工作地点
        worklocationservice.deleteByWorkTicketId(factory,workTicketId);
        if (StringUtils.isNotEmpty(workLocationList)) {
            workLocationList.stream().forEach(w->{
                w.setId(CodeTools.getCode32());
                w.setDeleteFlag(0);
                w.setCreateTime(currentTime);
            });
            worklocationservice.batchInsert(factory, workLocationList);
        }
    }

    public FourteenTables addByType(String type) {
        FourteenTables fourteenTables = new FourteenTables();

        // 1. 设置工作票类型
        WorkTicket workTicket = new WorkTicket();
        workTicket.setType(type);
        fourteenTables.setWorkTicket(workTicket);
        // 2. 设置当前用户信息
        fourteenTables.setCreateByName(getCurrUser().getName());
        fourteenTables.setCreateTime(currentTime);

        return fourteenTables;
    }

    public FourteenTables getById(SessionFactory factory, String id) {
        FourteenTables fourteenTables = new FourteenTables();

        // 1. 根据id查询工作票主票
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(id);
        WorkTicket workTicket = lineWorkTicketService.getSingle( factory, workTicketQuery);
        fourteenTables.setWorkTicket(workTicket);
        // 2. 根据workTicketId查询工作票详情
        WorkInfoQuery workInfoQuery = new WorkInfoQuery();
        workInfoQuery.setWorkTicketId(id);
        WorkInfo workInfo = workInfoService.getSingle(factory,workInfoQuery);
        fourteenTables.setWorkInfo(workInfo);
        // 3. 根据workTicketId查询工作班组
        WorkTeamQuery workTeamQuery = new WorkTeamQuery();
        workTeamQuery.setWorkTicketId(id);
        List<WorkTeam> workTeamList = workTeamService.getList(factory, workTeamQuery);
        fourteenTables.setWorkTeamList(workTeamList);
        // 4. 根据workTicketId查询工作班组成员
        WorkMemberQuery workMemberQuery = new WorkMemberQuery();
        workMemberQuery.setWorkTicketId(id);
        List<WorkMember> workMemberList = workMemberService.getList(factory, workMemberQuery);
        fourteenTables.setWorkMemberList(workMemberList);
        // 工作地点
        List<WorkLocationBean> worklocationlist = worklocationservice.getList(factory, id);
        fourteenTables.setWorkLocationList(worklocationlist);
        // 5. 根据status查看签名、待许可、工作待终结、工作票待终结的相关数据
        Integer status = workTicket.getStatus();
        if (status > TicketStatus.WRITE.getStatus()) {
            // 6.1 只要不是填写状态，都有签名
            WorkFlowQuery workFlowQuery = new WorkFlowQuery();
            workFlowQuery.setWorkTicketId(id);
            List<WorkFlow> workFlowList = workFlowService.getList(factory, workFlowQuery);
            fourteenTables.setWorkFlowList(workFlowList);
        }
        if (status >= TicketStatus.PERMIT.getStatus()) {
            // 6.2 状态是待许可,及以上的时候，查出待许可的信息
            WorkPermitQuery workPermitQuery = new WorkPermitQuery();
            workPermitQuery.setWorkTicketId(id);
            WorkPermit workPermit = workPermitService.getSingle(factory, workPermitQuery);
            fourteenTables.setWorkPermit(workPermit);
        }
        if (status >= TicketStatus.WORK_END.getStatus()) {
            // 6.3 状态是工作待终结,及以上的时候，查出工作终结的信息,以及工作票变更的相关信息
            WorkEndQuery workEndQuery = new WorkEndQuery();
            workEndQuery.setWorkTicketId(id);
            List<WorkEnd> workEndList = workEndService.getList(factory, workEndQuery);
            fourteenTables.setWorkEndList(workEndList);

            TicketChange ticketChange = ticketChangeService.getByWorkTicketId(factory, id);
            fourteenTables.setTicketChange(ticketChange);
        }

        return fourteenTables;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteById(SessionFactory factory, String id) {
        // 当id不为空的时候，才有数据删除
        if (!StringUtils.isEmpty(id)) {
            // 1. 主票信息删除
            lineWorkTicketService.deleteById(factory, id);
//            // 2. 工作票详情删除
//            workInfoService.deleteByWorkTicketId(factory, id);
//            // 3. 工作班组删除
//            workTeamService.deleteByWorkTicketId(factory, id);
//            // 4. 工作班组成员删除
//            workMemberService.deleteByWorkTicketId(factory, id);
//            // 5. 许可信息删除
//            workPermitService.deleteByWorkTicketId(factory, id);
//            // 6. 终结信息删除
//            workEndService.deleteByWorkTicketId(factory, id);
//            // 7. 签名信息删除
//            workFlowService.deleteByWorkTicketId(factory, id);
//            // 8. 工作票变更所有信息删除: (1) 工作票变更表 (2) 工作内容变更 (3) 工作延期变更 (4) 工作负责人变更 (5) 工作间断 (6) 工作成员变更 (7) 安全措施变更
//            ticketChangeService.deleteAllChangesByWorkTicketId(factory,id);
            // 9. 工作流删除
            String workflow = workFlowHandler.queryView(id, null);
            if (!StringUtils.isEmpty(workflow)) {
                workFlowHandler.end(id);
            }
        }
    }

    public String writeSubmitByWorkFlowTypeAndStatus(SessionFactory factory, FourteenTables fourteenTables, String workFlowType, Integer status) {
        WorkTicket workTicket = fourteenTables.getWorkTicket();
        String workTicketId = workTicket.getId();
        String code = workTicket.getCode();
        Map<String,String> form = new HashMap<>();
        form.put("EAM_USER",getCurrUser().getAccount());

        // 1. 保存当前的数据
        // 1.1 根据实际情况更新工作票状态
        workTicket.setStatus(status);
        if (StringUtils.isEmpty(workTicketId)) {
            // 1.2 id为空，数据是新增的，workTicketId在新增的时候获取
            workTicketId = this.insert(factory, fourteenTables);
        } else {
            this.update(factory, fourteenTables);
        }
        // 2. 进入工作流
        WorkflowProperties wfp = WorkflowProperties.init(workFlowType);
        workFlowHandler.start(wfp, workTicketId, code,workTicket.getTitle(), form);
        // 3. 记录操作人
        WorkFlow workFlow = new WorkFlow();
        workFlow.setWorkTicketId(workTicketId);
        workFlow.setType("填写人");
        workFlow.setAccount(getCurrUser().getAccount());
        workFlow.setName(getCurrUser().getName());
        workFlow.setPhone(getCurrUser().getPhone());
        workFlow.setOperationTime(currentTime);
        workFlow.setDeleteFlag(0);
        workFlowService.insert(factory, workFlow, TicketStatus.WRITE.getStatus());

        return workTicketId;
    }
}
